package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.service.IProductSkuService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-02-19
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private ProductDetailsMapper detailsMapper;

    @Autowired
    private ProductSkuMapper skuMapper;

    @Autowired
    private SkuStockMapper stockMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询商品SPU列表
     *
     * @return
     */
    @Override
    public List<Product> selectProductList() {
        List<Product> productList = baseMapper.selectProductList();
        /*if (!CollectionUtils.isEmpty(productList)) {
            for (Product product : productList) {
                String[] urls = product.getSliderUrls().split(",");
                List<String> urlList = Arrays.asList(urls);
                product.setSliderUrlList(urlList);
            }
        }*/
        return productList;
    }

    /**
     * 保存商品（商品信息、商品详情、商品SKU列表以及SKU库存）
     *
     * @param product
     */
    @Override
    @Transactional(rollbackFor = Exception.class)  //默认发生RuntimeException异常跟错误Error时事务回滚
    public void saveProduct(Product product) {
        //1.保存商品(SPU)信息
        //1.1 封装商品中基本信息
        product.setCreateBy(SecurityUtils.getUsername());
        product.setStatus(0);
        baseMapper.insert(product);
        //1.2 获取保存后商品ID
        Long productId = product.getId();

        //2.保存商品详情(详情页面中图片地址)
        List<String> detailsImageUrlList = product.getDetailsImageUrlList();
        if (!CollectionUtils.isEmpty(detailsImageUrlList)) {
            //2.1 创建商品详情对象
            ProductDetails productDetails = new ProductDetails();
            productDetails.setProductId(productId);
            //采用Stream流处理集合 将集合转为字符串，并以逗号分隔
            String imageUrls = detailsImageUrlList.stream().collect(Collectors.joining(","));
            productDetails.setImageUrls(imageUrls);
            //2.2 保存商品详情
            detailsMapper.insert(productDetails);
        }


        //3.保存商品SKU列表以及SKU库存
        List<ProductSku> skuList = product.getProductSkuList();
        if (!CollectionUtils.isEmpty(skuList)) {
            int index = 0;
            for (ProductSku sku : skuList) {
                //3.1 设置SKU的编号 规则：商品ID_索引值
                sku.setSkuCode(productId + "_" + index++);
                //3.2 设置SKU的名称 商品名称+规格参数
                sku.setSkuName(product.getName() + sku.getSkuSpec());
                //3.3 关联商品ID
                sku.setProductId(productId);
                //3.4 设置初始状态 0
                sku.setStatus(0);
                //3.5 创建者信息
                sku.setCreateBy(SecurityUtils.getUsername());
                //3.6 保存SKU商品
                skuMapper.insert(sku);
                Long skuId = sku.getId();
                //4. 保存SKU对应库存
                Integer stockNum = sku.getStockNum();
                //4.1 创建库存对象
                SkuStock skuStock = new SkuStock();
                skuStock.setSkuId(skuId);
                skuStock.setTotalNum(stockNum);
                skuStock.setAvailableNum(stockNum);
                skuStock.setLockNum(0);
                skuStock.setSaleNum(0);
                skuStock.setStatus(0);
                skuStock.setCreateBy(SecurityUtils.getUsername());
                stockMapper.insert(skuStock);
            }
        }
    }

    /**
     * 商品上下架
     *
     * @param productId 商品ID
     * @param status    状态 1：上架  -1：下架
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long productId, Integer status) {
        //1.修改商品状态
        Product product = new Product();
        product.setId(productId);
        product.setStatus(status);
        baseMapper.updateById(product);
        //2.修改SKU状态（多个） update sku set status = ? where product_id = ?
        skuMapper.update(
                null,
                new LambdaUpdateWrapper<ProductSku>().eq(ProductSku::getProductId, productId).set(ProductSku::getStatus, status)
        );

        //3.修改SKU库存状态（多个）
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getProductId, productId);
        queryWrapper.select(ProductSku::getId);
        List<ProductSku> skuList = skuMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(skuList)) {
            for (ProductSku sku : skuList) {
                stockMapper.update(
                        null,
                        new LambdaUpdateWrapper<SkuStock>().eq(SkuStock::getSkuId, sku.getId()).set(SkuStock::getStatus, status)
                );
                //TODO 如果是上架，将商品SKUID存入Redis中bitmap位图中
                if(status==1){
                    String key = "product:sku:data";
                    redisTemplate.opsForValue().setBit(key, sku.getId(), true);
                }
            }
        }
    }

    /**
     * 批量删除SPU相关信息
     *
     * @param ids 商品ID列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeProduct(List<Long> ids) {
        //1.根据商品ID列表批量 删除商品
        baseMapper.deleteBatchIds(ids);

        //2.根据商品ID列表批量 删除商品详情
        detailsMapper.delete(new LambdaQueryWrapper<ProductDetails>().in(ProductDetails::getProductId, ids));

        //3.删除SKU库存
        //3.1 根据商品ID查询SKU列表得到要删除SKUID列表
        List<ProductSku> skuList = skuMapper.selectList(
                new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, ids).select(ProductSku::getId)
        );


        //3.2 删除库存
        if (!CollectionUtils.isEmpty(skuList)) {
            //3.2.1 获取要删除的SKUID列表
            //List<Long> skuIdList = skuList.stream().map((ProductSku sku) -> {
            //    Long skuId = sku.getId();
            //    return skuId;
            //}).collect(Collectors.toList());

            //List<Long> skuIdList = skuList.stream().map(sku -> {
            //    return sku.getId();
            //}).collect(Collectors.toList());

            List<Long> skuIdList = skuList.stream().map(ProductSku::getId).collect(Collectors.toList());

            //3.2.2 删除库存
            stockMapper.delete(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, skuIdList));


            //4.根据商品ID列表批量 删除商品SKU列表
            skuMapper.delete(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, ids));
        }

    }

    /**
     * 查询轮播图
     *
     * @param productId
     * @return
     */
    @Override
    public String[] getSliderUrlList(Long productId) {
        Product product = baseMapper.selectById(productId);
        String sliderUrls = product.getSliderUrls();
        if (!ObjectUtils.isEmpty(sliderUrls)) {
            //1.png,2.png
            return sliderUrls.split(",");
        }
        return new String[0];
    }
}
